<?php

namespace App\Resource;


use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;

class ApiResource
{
    protected $resource;
    protected $exception;
    protected $message;
    protected $code;

    /**
     * @var ContainerInterface
     */
    public $container;

    public function __construct($resource, string $message = null, int $code = 200)
    {
        if ($resource instanceof \Throwable) {
            $this->exception = $resource;
            $this->code = $resource->getCode();
            $this->message = $resource->getMessage();
            $resource = [];
        } else {
            $this->code = $code;
            $this->message = $message;
        }
        $this->resource = $resource;
        $this->container = ApplicationContext::getContainer();
    }

    /**
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    public function with()
    {
        $data = $this->withDefault();
        if ($this->exception) {
            $data = $this->withErrorMessage($data);
        }

        return $this->container->get(ResponseInterface::class)->json($data);

    }

    protected function withErrorMessage(array $data = [])
    {
        $resource = $this->exception;
        if (config('debug')) {
            $data['file'] = $resource->getFile();
            $data['line'] = $resource->getLine();
            $data['trace'] = $resource->getTrace();
        }
        return $data;
    }

    public function toArray()
    {
        $resource = $this->resource;
        if (is_null($resource)) {
            return [];
        }
        return $resource;
    }

    protected function withDefault()
    {
        return [
            'code' => $this->code ?? 200,
            'message' => $this->message ?? '',
            'data' => $this->resource ?? [],
        ];
    }


}
